/* eslint-disable no-param-reassign */
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Alert, Button, Input, Tag, theme } from 'antd';
import pinyin from 'pinyin';
import { TweenOneGroup } from 'rc-tween-one';
import { useEffect, useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

// 过滤函数
function filterByPinyin(data, keyword) {
  const pinyinres = pinyin(data, {
    style: 'normal', // 使用普通风格的拼音
  }).join('');
  // 检查拼音是否包含关键字
  return pinyinres?.toUpperCase().includes(keyword);
}

const TagGroup = () => {
  const { token } = theme.useToken();
  const [tags, setTags] = useState(
    localStorage.getItem('TAG')
      ? JSON.parse(localStorage.getItem('TAG'))
      : ['示例:项目'],
  );
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [search, setSearch] = useState();

  useEffect(() => {
    localStorage.setItem('TAG', JSON.stringify(tags));
  }, [tags]);

  const {
    initialState: { curData },
    setInitialState,
  } = useModel('@@initialState');

  const inputRef = useRef(null);
  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);
  const handleClose = (removedTag) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    console.log(newTags);
    setTags(newTags);
  };
  const showInput = () => {
    setInputVisible(true);
  };
  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      setTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };
  const forMap = (tag) => (
    <span
      key={tag}
      style={{
        display: 'inline-block',
      }}
    >
      <Tag
        closable
        onClose={(e) => {
          e.preventDefault();
          handleClose(tag);
        }}
        style={{
          borderRadius: 10,
          padding: 8,
          fontSize: 14,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          cursor: 'pointer',
        }}
        onClick={() => {
          let newData = [];
          const additem = {
            name: null,
            progress: 0,
            editting: true,
            id: uuidv4(),
          };
          if (curData.some((it) => it.project === tag)) {
            newData = [...curData]?.map((it) => {
              if (it.project === tag) {
                it = {
                  ...it,
                  list: [...it.list, additem],
                };
              }
              return it;
            });
            setTimeout(() => {
              const dom = document.getElementById(additem.id);
              dom?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
              dom?.focus?.();
            }, 600);
          } else {
            newData = [
              ...curData,
              {
                project: tag,
                id: uuidv4(),
                list: [additem],
              },
            ];
            setTimeout(() => {
              const dom = document.getElementById(additem.id);
              dom?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
              dom?.focus?.();
            }, 600);
          }
          setInitialState((s) => ({
            ...s,
            curData: newData,
          }));
        }}
      >
        {tag}
      </Tag>
    </span>
  );
  const tagChild = tags
    .filter((it) => {
      if (!search) {
        return true;
      } else {
        return filterByPinyin(it.toUpperCase(), search?.toUpperCase());
      }
    })
    .map(forMap);
  const tagPlusStyle = {
    background: token.colorBgContainer,
    borderStyle: 'dashed',
    width: 180,
    padding: '8px 12px',
    borderRadius: 10,
    fontSize: 16,
    flexShrink: 0,
    margin: 0,
  };
  return (
    <div
      style={{
        margin: '-6px -12px 6px -12px',
        padding: 12,
        position: 'sticky',
        top: 0,
        zIndex: 99,
        backgroundColor: '#f0f0f988',
        backdropFilter: 'blur(6px)',
      }}
    >
      {!localStorage.getItem('ATIP') && (
        <Alert
          type="info"
          showIcon
          message="点击项添加事项"
          style={{ marginBottom: 12 }}
          closable={{
            closeIcon: (
              <Button size="small" type="text">
                知道了
              </Button>
            ),
          }}
          onClose={() => {
            localStorage.setItem('ATIP', 'true');
          }}
        ></Alert>
      )}

      <div
        style={{
          display: 'flex',
          gap: 12,
        }}
      >
        {inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            size="large"
            variant="borderless"
            value={inputValue}
            onChange={handleInputChange}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
            placeholder="Enter/点击别处 添加"
            allowClear
            style={{
              width: 180,
              backgroundColor: '#ffffff',
              height: 40,
              borderRadius: 10,
              flexShrink: 0,
            }}
          />
        ) : (
          <Tag
            onClick={showInput}
            style={{
              ...tagPlusStyle,
              display: 'flex',
              justifyContent: 'flex-start',
              alignItems: 'center',
            }}
          >
            <PlusOutlined style={{ marginRight: 8 }} /> 添加项
          </Tag>
        )}
        <Input
          size="large"
          allowClear
          style={{ flex: 1, ...tagPlusStyle, border: 'none', fontSize: 16 }}
          variant="borderless"
          placeholder="筛选项,支持拼音"
          prefix={<SearchOutlined style={{ fontSize: 17 }} />}
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
          }}
        ></Input>
      </div>

      <div
        style={{
          marginTop: 12,
          display: tags.length > 0 ? 'block' : 'none',
        }}
      >
        <TweenOneGroup
          enter={{
            scale: 0.8,
            opacity: 0,
            type: 'from',
            duration: 100,
          }}
          leave={{
            opacity: 0,
            width: 0,
            scale: 0,
            duration: 200,
          }}
          onEnd={(e) => {
            if (e.type === 'TagGroupear' || e.type === 'enter') {
              e.target.style = 'display: inline-block';
            }
          }}
        >
          {tagChild}
        </TweenOneGroup>
      </div>
    </div>
  );
};
export default TagGroup;
